20. psycopg2: fetching results

psycopg2 demo 3 Heading

psycopg2: fetching results

ND004 C01 L02 26 Psycopg2 Demo 3

Let's practice! Now complete Exercise 3.

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter-lab
  • Opened files (when workspace is loaded): n/a

That marks the end of our lessons on psycopg2….

Now there is time for a few final remarks.

ND004 C01 L02 24 Psycopg2 Transition

That's right.

Now that you know Flask, Postgres, and psycopg2, you can now create a database-backed web application without learning anything else! You can just send SQL statements directly to the Postgres server from your web server, written in Python, and be set to go!

But should we…?

Writing SQL directly is a fairly clunky way of doing web development. It's useful to learn some higher level libraries that let us interact with a database, using Python classes and expressions. Let's get to learn one of the most powerful Python libraries for interacting with databases: SQLAlchemy .

Steps for getting a database-backed web application up and running

Here is an overview of the list of tasks we'll need to do for a given web app to run with a database.

1. Create a database

Using createdb in Postgres.

2. Establish a connection to the database

We can connect to a Postgres server from a Python web server using pyscopg2 with psycopg2.connect() .

3. Define and create your data schema

Execute CREATE TABLE commands to create the tables and define the schema (attributes, data types, etc) that will define what data gets housed for our web app.

4. Seed the database with initial data

(Optional) Give the database some initial data, e.g. test data for doing local development.

5. Create routes and views

Create routes in our server that will serve pages (views) to the client. Write up our HTML, CSS, and Javascript in our views.

Then finally, to get our web app running,

6. Run the server

Get the web server running.

7. Deploy the server to the web.

… and that is, generally, how we would build a web application backed by a database.